package com.thingsgrid.device.feign;

import com.thingsgrid.appmanager.entity.FeignVo;
import com.thingsgrid.device.entity.Device;
import lombok.AllArgsConstructor;
import org.springblade.core.tool.api.R;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

//import java.util.ArrayList;

@RestController
@AllArgsConstructor
public class TopmFeignImpl implements TopmFeign {
	private MongoTemplate mongoTemplate;

	@Override
	public R<Map<String, Object>> GetSomeDeviceInfo(FeignVo vo) {
		return R.data(GetSomeDeviceList(vo.getDeviceName(), vo.getDeviceIds(), vo.getFlag(), vo.getCurrent(), vo.getSize()));
	}


	private Map<String, Object> GetSomeDeviceList(String deviceName, List<String> devicelist, int flag, int pageNum, int pageSize) {
		long totalSize;
		List<Device> deviceList;
		Map<String, Object> map = new HashMap<>();
		if (deviceName == null || deviceName.equals("")) {
			Query query = null;
			if (devicelist != null) {
				if (flag == 0) {
					query = new Query().addCriteria(Criteria.where("device_id").nin(devicelist)).skip((pageNum - 1) * pageSize).limit(pageSize);
				} else {
					query = new Query().addCriteria(Criteria.where("device_id").in(devicelist)).skip((pageNum - 1) * pageSize).limit(pageSize);
				}

			} else {
				query = new Query().skip((pageNum - 1) * pageSize).limit(pageSize);
			}

			deviceList = mongoTemplate.find(query, Device.class, "device");
			totalSize = mongoTemplate.count(query, Device.class, "device");
			map.put("device", deviceList);
			map.put("total", totalSize);
		} else {
			Query query = null;
			Pattern pattern = Pattern.compile("^.*" + deviceName + ".*$", Pattern.CASE_INSENSITIVE);
			if (devicelist != null) {
				if (flag == 0) {
					query = new Query(Criteria.where("deviceName").regex(pattern).and("device_id").nin(devicelist)).skip((pageNum - 1) * pageSize).limit(pageSize);
				} else {
					query = new Query(Criteria.where("deviceName").regex(pattern).and("device_id").in(devicelist)).skip((pageNum - 1) * pageSize).limit(pageSize);
				}
			} else {
				query = new Query(Criteria.where("deviceName").regex(pattern)).skip((pageNum - 1) * pageSize).limit(pageSize);
			}
			deviceList = mongoTemplate.find(query, Device.class, "device");
			totalSize = mongoTemplate.count(query, Device.class, "device");
			map.put("device", deviceList);
			map.put("total", totalSize);
		}
		return map;
	}
}
